package com.srit.base.struts2.action;

import java.lang.reflect.InvocationTargetException;

import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ModelDriven;
import com.srit.base.service.BaseService;
import com.srit.base.service.EntityIdReflect;

/**
 * CRUD action封装
 * 
 * @author guan
 * 
 */
public abstract class CrudAction extends BaseAction implements ModelDriven {
	@Autowired(required = true)
	private BaseService baseService;
	private EntityIdReflect entityReflect;
	private String entityName;

	@Override
	public void prepare() throws Exception {
		Class clz = getModel().getClass();
		entityName = clz.getName()
				.substring(clz.getName().lastIndexOf(".") + 1).trim();
		baseService.setEntityName(entityName);
	}

	public String form() throws IllegalAccessException,
			IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, NoSuchFieldException {
		Object idValue = entityReflect.reflectIdFromObject(getModel());
		if (idValue != null) {
			Integer intValue = (Integer) idValue;
			page.getResult().put(entityName, baseService.getByIntId(intValue));
		}
		return "form";
	}

	public String save() {
		baseService.save(getModel());
		return "save";
	}

	public String update() {
		baseService.update(getModel());
		return "update";
	}

	public String page() {
		baseService.page(getModel(), page);
		return "page";
	}

	public String delete() {
		baseService.delete(getModel());
		return "delete";
	}

}
